<!-- 点击显示个人信息，包括报告和登出按钮 -->
<template>  
    <div>  
      <!-- 头像固定在右上角 -->  
      <div class="fixed-avatar" @click="dropdownVisible = !dropdownVisible">  
        <img :src="avatarUrl" alt="Avatar" />  
        <!-- 下拉菜单 -->  
        <el-menu  
          v-show="dropdownVisible"  
          class="avatar-dropdown-menu"  
          background-color="#fff"  
          text-color="#333"  
          active-text-color="#409EFF"  
          @select="handleMenuSelect"  
        >  
          <el-menu-item class="menu-item" index="profile">个人信息</el-menu-item>  
          <el-menu-item class="menu-item" index="report">报告/申请</el-menu-item>  
          <el-menu-item class="menu-item" index="logout">登出</el-menu-item>
        </el-menu>  
      </div> 
      <!-- 个人信息弹窗 -->  
      <el-dialog  
        title="个人信息"  
        v-model="dialogVisible"  
        width="50%"  
        @close="dialogVisible = false"  
      >  
        <div class="profile-info">  
          <!-- 头像上传 -->  
          <div class="avatar-upload">  
            <img :src="avatarUrl" alt="Avatar" />  
            <el-upload  
              class="avatar-uploader"  
              action="https://apifoxmock.com/m1/4767131-4420546-default/api/avatar_upload"  
              accept=".jpg, .jpeg, .png"
              :show-file-list="false"  
              :on-success="handleAvatarUploadSuccess" 
              :on-error="handleAvatarUploadError" 
              :before-upload="beforeAvatarUpload"  
            >  
              <el-button size="small" type="primary">上传头像</el-button>  
            </el-upload>  
          </div>  
          <!-- 个人信息展示 -->  
          <div class="profile-details">  
            <p><strong>警号:</strong> {{ uid }}</p>  
            <p><strong>姓名:</strong> {{ name }}</p>  
            <p><strong>邮箱:</strong> {{ email }}</p>  
            <p><strong>所属单位:</strong> {{ organization }}</p>  
          </div>  
        </div>  
      </el-dialog>   
    </div>  
  </template>  
    
  <script>  
  export default {  
    data() {  
      return {  
        avatarUrl: 'logo.jpg', // 初始头像URL
        avatarBase64: '', // 用于存储Base64编码的图片
        dropdownVisible: false,
        dialogVisible: false,
        uid: '',  
        name: '',  
        email: sessionStorage.getItem('userInfo'),  
        organization: '',  
      };  
    },  
    mounted() {  
        this.fetchProfileInfo();  
    },  
    methods: {  
        /* imgUrlToBase64(url) {
            return new Promise((resolve, reject) => {
            if (!url) {
                reject('请传入url内容')
            }
            if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(url)) {
            // 图片地址
            let image = new Image()
            // 设置跨域问题
            image.setAttribute('crossOrigin', 'anonymous')
            // 图片地址
            image.src = url
            image.onload = () => {
                const canvas = document.createElement('canvas')
                const ctx = canvas.getContext('2d')
                canvas.width = image.width
                canvas.height = image.height
                ctx.drawImage(image, 0, 0, image.width, image.height)
                // 获取图片后缀
                const ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase()
                // 转base64
                const dataUrl = canvas.toDataURL(`image/${ext}`)
                resolve(dataUrl || '')
                }
            }       else {
                    // 非图片地址
                    reject('非(png/jpe?g/gif/svg等)图片地址');
                }
            })
        }, */

    async convertUrlToBase64(url) {  
      const response = await fetch(url)
      const blob = await response.blob()
      return new Promise((resolve, reject) => {  
        const reader = new FileReader()
        reader.onloadend = () => resolve(reader.result)
        reader.onerror = reject 
        reader.readAsDataURL(blob)
      })
    },  

    async fetchProfileInfo() {  
      console.log(this.email)
      this.axios.get('https://apifoxmock.com/m1/4767131-4420546-default/api/get_profile_info',{ params: { email:this.email} })
      .then(async (response) => {  
        this.uid = response.data.uid
        this.name = response.data.name
        this.organization = response.data.organization
        if (response.data.avatarUrl) {  
          this.avatarUrl = response.data.avatarUrl // 如果后端返回了新的头像URL，则更新原始的URL  
          // 调用convertUrlToBase64函数将URL转换为Base64  
          // this.avatarBase64 = await this.convertUrlToBase64(this.avatarUrl);
          // this.avatarUrl = this.avatarBase64;
        }  
      }).catch((error) => {  
        console.error('Error fetching profile info:', error)
      })
    },  
        handleAvatarUploadSuccess(response, file, fileList) {  
          // 假设服务器返回的数据中包含新的头像URL  
          if(response.avatarUrl) {
            console.log(response.avatarUrl)
            this.avatarUrl = response.avatarUrl
            // 调用convertUrlToBase64函数将URL转换为Base64  
            // this.avatarBase64 = this.convertUrlToBase64(this.avatarUrl)
            // this.avatarUrl = this.avatarBase64
            this.$message.success(`${file.name} 上传成功`)
          }
          /* convertUrlToBase64('https://example.com/path/to/image.jpg')  
          .then(base64 => {  
            console.log(base64); // 输出Base64编码的图片数据  
            // 你可以将这个Base64编码赋值给img标签的src属性，或者发送到后端  
          })  
          .catch(error => {  
            console.error('Error converting URL to Base64:', error);  
          });*/
        else this.avatarUrl = 'logo.jpg';
      },  
      handleUploadError(err, file) {
        this.$message.error(`${file.name} 上传失败`)
      },
      beforeAvatarUpload(file) {  
        // 可以在这里添加文件类型和大小的验证逻辑  
        let sizeByMb = file.size / 1024 / 1024;
        if (sizeByMb > 2) {
          this.$message.warning("上传文件不能超过2M")
          return false
        }
        if (file.type != 'image/jpeg' && file.type != 'image/png') {
          this.$message.warning("只能上传图片")
          return false
        }
        return true
      },  
      handleMenuSelect(index) {  
        this.dropdownVisible = false;  
        switch (index) {  
          case 'profile':  
            // 处理个人信息点击事件
            this.dialogVisible = true;
            break;  
          case 'report':  
            // 处理报告点击事件
            this.$router.push('/plcfunction');
            break;  
          case 'logout':  
            // 处理登出点击事件  
            // 从 sessionStorage 删除所有保存的数据
            sessionStorage.clear();
            this.$router.push('/prelogin');
            break;  
          default:  
            break;  
        }  
      }  
    }  
  };  
  </script>  
    
  <style scoped>  
  .fixed-avatar {  
    position: fixed;  
    right: 20px;  
    top: 20px;  
    cursor: pointer;  
  }  
    
  .fixed-avatar img {  
    width: 50px;  
    height: 50px;  
    border-radius: 50%;  
  }  
    
  .avatar-dropdown-menu {  
    position: absolute;  
    right: 0;  
    top: 60px; /* 头像高度加上一些间距 */  
    width: 100px;  
    z-index: 1000;  
    background: rgba(255, 170, 78, 0.7);
    border: 2px solid orange;
  }  

  .menu-item:hover {
    background: rgba(254, 145, 29, 0.7)
  }

  .avatar-upload img {  
    width: 60px;  
    height: 60px;  
    border-radius: 50%;  
  }  
  </style>